const {BrowserWindow, ipcMain, dialog} = require('electron');
const os = require('os');
const path = require('path');
const fs = require('fs');
const db = require('../services/db');

let selectedQuesIds = [];
let filterType = '';
let filterRating = '';

function registerQUESIpc() {
    // 获取筛选条件
    ipcMain.handle('filter:get', () => {
        return {
            type: filterType,
            rating: filterRating
        };
    });

    // 确认勾选考题（顺便设置筛选条件）
    ipcMain.on('ques:confirmSelected', (event, {ids, type, rating}) => {
        selectedQuesIds = ids || [];
        if (type) {
            filterType = type;
        }
        if (rating) {
            filterRating = rating;
        }
        console.log('confirmSelected:', selectedQuesIds);
        console.log('filterSet:', {
            'filterType': filterType,
            'rating': rating
        })
    });

    // 获取已勾选的考题
    ipcMain.handle('ques:getSelected', async () => {
        return await db.getQuesListByIds(selectedQuesIds);
    });

    // 获取已勾选的考题id
    ipcMain.handle('ques:getSelectedIds', async () => {
        return selectedQuesIds;
    });

    // 清空已勾选考题
    ipcMain.on('ques:clearSelected', () => {
        selectedQuesIds = [];
    });

    // 调整已勾选考题的排序
    ipcMain.on('ques:updateSelectedOrder', (event, newOrderIds) => {
        selectedQuesIds = newOrderIds;
        console.log('updateSelectedOrder:', newOrderIds);
    });

    // 导出pdf
    ipcMain.handle('ques:generatePdf', async () => {
        const win = BrowserWindow.getFocusedWindow(); // 当前窗口
        if (!win) return false;

        try {
            // 打开保存对话框
            const timestamp = Date.now(); // 获取当前毫秒级时间戳
            const count = selectedQuesIds.length;
            const filename = `${timestamp}_${count}.pdf`;
            const {filePath, canceled} = await dialog.showSaveDialog(win, {
                title: '导出PDF',
                defaultPath: path.join(os.homedir(), 'Desktop', filename),
                filters: [{name: 'PDF 文件', extensions: ['pdf']}]
            });

            if (canceled || !filePath) {
                return {status: 'cancelled'}; // 用户取消
            }

            // 生成 PDF buffer
            const pdfData = await win.webContents.printToPDF({
                landscape: false,
                printBackground: true,
                pageSize: 'A4',
            });

            // 写入文件
            fs.writeFileSync(filePath, pdfData);
            return {status: 'success'};
        } catch (err) {
            console.error('PDF导出失败：', err);
            return {status: 'error', message: err.message};
        }
    });
}

module.exports = registerQUESIpc;